package com.xh.baselibrary.tts

import com.xh.baselibrary.log.XLog
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class TTSPlayer(val ttsEngine: TTSEngine) {
    @Volatile
    var isPlaying = false

    var currentTTSRequest: TTSRequest? = null
    fun playTTS(ttsRequest: TTSRequest) {
        XLog.i("playTTS----> ${ttsRequest.text}")
        GlobalScope.launch {
            synchronized(ttsRequest) {
                currentTTSRequest = ttsRequest
                if (!ttsRequest.isCancel) {
                    ttsRequest.ttsPlayCallback?.apply {
                        onTTSStart(ttsRequest)
                    }
                }
            }
            isPlaying = true
            //模拟播报
            delay(ttsRequest.text.length * 500L)
            isPlaying = false
            currentTTSRequest = null
            val isFinish = synchronized(ttsRequest) {
                if (!ttsRequest.isCancel) {
                    ttsRequest.isFinish = true
                    true
                } else false
            }
            if (isFinish) {
                ttsRequest.ttsPlayCallback?.apply {
                    onTTSFinish(ttsRequest)
                }
                ttsEngine.dispatcher.promoteAndExecute()
            }
        }
    }

    fun cancelTTS(ttsRequest: TTSRequest) {
        XLog.i("cancelTTS----> ${ttsRequest.text}")
        if(ttsRequest == currentTTSRequest){
            //执行停止播报
            XLog.i("执行停止播报----> ${ttsRequest.text}")
            currentTTSRequest = null
        }
        synchronized(ttsRequest) {
            if (ttsRequest.isFinish) {
                return
            }
            ttsRequest.isCancel = true
            ttsRequest.ttsPlayCallback?.apply {
                onCancel(ttsRequest)
            }
        }
        ttsEngine.dispatcher.promoteAndExecute()
    }

}